import { Component, OnInit, AfterViewInit, OnDestroy, ViewChild } from '@angular/core';
import { DateOptionService } from '../../../share/date-option.service';
import { DeviceService } from '../../../share/device.service';
import { EChartOption, ECharts } from 'echarts-ng2';
import { Subscription } from 'rxjs/Rx';
import { Device, Select, DataFilter, ChartsQueryCondition, FormatDate, ChartOption } from '../../../classes/Device';
import { URLSearchParams, Jsonp, Http } from '@angular/http';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { FormControl } from '@angular/forms';
import { EmitData } from 'app/time-type/time-type.component';
import { environment } from 'environments/environment.prod';
import { Curver } from 'app/classes/BackData';



@Component({
  selector: 'app-data-query',
  templateUrl: './data-query.component.html',
  styleUrls: ['./data-query.component.css']
})
export class DataQueryComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('echarts') echarts: ECharts;
  /**
   * 初始化一些配置
   * @param {object} datepickerOpts-> 从service中获取定义时间控件的配置参数
   * @param {object} begindate-> 初始化查询时间
   * @param {object} enddate-> 初始化查询时间
   * @param {Subscription} subscription-> 定义观察者，在ngOnDestroy生命周期中取消观察
   * @param {Array<object>} selects-> 定义数据类型的可选参数的名字和值
   * @param {Device} deviceInfo-> 左侧点击后传来device信息
   * @param {string} type-> 初始化数据类型选项的值
   * @param {EChartOption} option-> 定义曲线的配置参数
   * @param {Date} _now-> 定义曲线横坐标的开始点
   * @param {Date} now_-> 定义曲线横坐标的结束点
   * @param {string} url-> 初始化本页曲线请求的数据的地址
   * @param {object} _params-> 定义查询的条件
   * @param {Observable} observable-> 定义一个流，接收http.get的返回
   * @param {Array<any>} chartData-> 定义曲线所需要的X轴的值
   * @param {Array<string>} times-> 定义列表中的时间列
   * @param {object} data-> 返回的要刷在列表上的数
   */
  type = '1001';
  _params = {
    'meterID': '',
    'begindate': new Date().toLocaleDateString(),
    'enddate': new Date().toLocaleDateString(),
    'datatype': this.type
  }
  begindate: object;
  enddate = this.begindate;

  public subscription: Subscription;
  public selects: Array<Select>;
  public deviceInfo: Device;


  public option: EChartOption ;
  _now = new Date().setHours(0, 0, 0, 0);
  now_ = new Date().setHours(23, 59, 59, 999);
  public observable: Observable<any>;

  // url = '/DSMService/GetCurver';
  url = environment.httpUrl;

  public chartData: Array<any>;

  public times: Array<string> = [
    '1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00', '合计',
  ];
  public listData: any;

  constructor(
    public dateOption: DateOptionService,
    public deviceService: DeviceService,
    public http: Http
  ) {

  }

  ngOnInit() {
    // 初始化时间
    const date = new Date();
    this.begindate = {
      formatted: new FormatDate(date).formatToString()
    }
    // 初始化数据类型选项
    this.selects = [
      new Select('电压', '1001'),
      new Select('电流', '1002'),
      new Select('电量', '1003'),
      new Select('功率因数', '1004'),
      new Select('有功功率', '1005'),
      new Select('无功功率', '1006'),
      new Select('电流电压不平衡', '1007'),
    ];
    // 初始化设备信息
    this.deviceInfo = this.deviceService.getDeviceInfo();

    // 当观察到设备发射来的数据有变化时。得到曲线的的数据
    this._params.meterID = this.deviceInfo.meterID;
    this._params.datatype = this.type;
    this.observable = this.http.get(this.url, { params: this._params }).map( res => JSON.parse(res.json()) );
    this.observable.subscribe(
      data => {
        if (data.data) {
          const chartOption = new ChartOption(
            data.data,
            this._params.datatype,
            new Date(this._params.begindate).setHours(0, 0, 0, 0),
            new Date(this._params.enddate).setHours(23, 59, 59, 999)
          );
          this.echarts.setOption(chartOption.getOption());
        } else {
          console.log(data.msg)
        }
      },
      err => console.log(err)
    );

    // 得到列表的参数
    this.listData = {
      time: new Date(),
      positiveActive: {
        AM: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 999],
        PM: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 999]
      },
      positiveReactive: {
        AM: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 999],
        PM: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 999]
      }
    }
  }
  ngAfterViewInit(): void {
    this.subscription = this.deviceService.getMessage().subscribe(msg => {
      this.deviceInfo = msg;
      this._params.meterID = this.deviceInfo.meterID;
      this.observable = this.http.get(this.url, { params: this._params }).map( res => JSON.parse(res.json()) );
      this.observable.subscribe(
        data => {
          if (data.data) {
            const chartOption = new ChartOption(
              data.data,
              this._params.datatype,
              new Date(this._params.begindate).setHours(0, 0, 0, 0),
              new Date(this._params.enddate).setHours(23, 59, 59, 999)
            );
            this.echarts.setOption(chartOption.getOption());
          } else {
            console.log(data.msg)
          }
        },
        err => {
          console.log(err);
          alert('后台没有返回数据');
        }
      );
    })
  }
  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  getDate(event: EmitData) {
    if (event.type === 'start') {
      this._params.begindate = event.event.formatted;
    } else {
      this._params.enddate = event.event.formatted;
    }
  }
  condition(value: ChartsQueryCondition) {
    this._params.datatype = value.datatype;
    this._params.enddate = this._params.begindate;
    this.echarts.clear();
    this.observable = this.http.get(this.url, { params: this._params }).map( res => JSON.parse( res.json() ) );
    this.observable.subscribe(
      data => {
        if (data.data) {
          const chartOption = new ChartOption(
            data.data,
            this._params.datatype,
            new Date(this._params.begindate).setHours(0, 0, 0, 0),
            new Date(this._params.enddate).setHours(23, 59, 59, 999)
          );
          this.echarts.setOption(chartOption.getOption());
        } else {
          console.log(data.msg)
        }
      },
      err => {
        console.log(err);
        alert('后台没有返回数据');
      }
    );
  }
}
